let code = require('../constant/code');
let express = require('express');
let router = express.Router();
let async = require('async');
const crypto = require('crypto');
let commonDao = require('../dao/commonDao');
let recordDao = require('../dao/recordDao');
let enumeration = require('../constant/enumeration');
let userDao = require('../dao/userDao');
let utils = require('../util/utils');
let gameServerInterfaceServices = require('../services/gameServerInterfaceServices');


// -------------------------------------公用相关-----------------------------------
router.post('/retransmissionToGameServer', function (req, res, next) {
    if (!req.session.uid) {
        res.send({ code: code.INVALID_UERS });
        return;
    }
    if (!req.session.permission) {
        res.send({ code: code.PERMISSION_NOT_ENOUGH });
        return;
    }

    let route = req.body.route;
    let data = {};
    for (let key in req.body) {
        if (key === 'route') continue;
        data[key] = req.body[key];
    }
    data.permission = req.session.permission;
    data.uid = req.session.uid;

    gameServerInterfaceServices.retransmissionToGameServer(route, data, function (err, data) {
        if (!!err) {
            res.send({ code: code.FAIL });
        } else {
            if (!data) {
                res.send({ code: code.OK });
            } else {
                res.send(data);
            }
        }
    })
});

// ------------------------------------帐号相关-----------------------------------


router.post('/updateAdminPassword', function (req, res, next) {
    if (!req.session.uid) {
        res.send({ code: code.INVALID_UERS });
        return;
    }

    let newPassword = req.body.password;
    if (!newPassword || newPassword.length > 20) {
        res.end({ code: code.REQUEST_DATA_ERROR });
        return;
    }
    commonDao.findOneData('adminModel', { uid: req.session.uid }, function (err, result) {
        if (!!err) {
            res.send({ code: err });
        } else {
            if (!result) {
                res.send({ code: code.HALL.NOT_FIND });
            } else {
                newPassword = crypto.createHash('md5').update(newPassword, "utf-8").digest('hex');
                commonDao.updateData("adminModel", { uid: req.session.uid }, { password: newPassword }, function (err) {
                    res.send({ code: !!err ? err : code.OK });
                })
            }
        }
    })
});

// ------------------------------------记录相关-----------------------------------
function checkRecordPermission(model, permission) {
    if (!permission) {
        return false;
    }

    if (permission == -1) {
        return true;
    }

    // 检查权限
    if (model === 'adminModel' || model === 'accountModel') {
        if (permission !== -1) {
            return false;
        }
    } else if (model === "rechargeModel" || model === "orderModel" || model === "userGameRecordModel" || model == "userScoreDataModel") {
        return true;
    } else if (model === "limitIPModel" || model === "userNoteModel" || model === "userPayModel" || model === "userPayDetailModel") {
        return true;
    }
    else if (model === "userModel") {
        if ((permission & enumeration.userPermissionType.USER_MANAGER) === 0) {
            return false;
        }
    } else if (model === "configModel" || model === "gameTypeModel") {
        if ((permission & enumeration.userPermissionType.USER_SYSTEM_MANAGER) === 0) {
            return false;
        }
    } else if (model === "adminGrantRecordModel" ||
        model === "unionModel" || model === "userScoreChangeRecordModel") {
        if ((permission & enumeration.userPermissionType.DATA_MANAGER) === 0) {
            return false;
        }
    } else if (model === "gameControlDataModel") {
        if ((permission & enumeration.userPermissionType.GAME_CONTROL) === 0) {
            return false;
        }
    } else {
        return false;
    }
    return true;
}

function recordChangeNotify(model) {
    if (model === "gameTypeModel") {
        gameServerInterfaceServices.reloadParameterNotify([model], function (err) {
            if (!!err) {
                console.error(err);
            }
        })
    } else if (model === "configModel") {
        gameServerInterfaceServices.reloadParameterNotify([model], function (err) {
            if (!!err) {
                console.error(err);
            }
        })
    }
}
router.post('/getRecord', function (req, res, next) {
    if (!req.session.uid) {
        res.send({ code: code.INVALID_UERS });
        return;
    }
    if (!checkRecordPermission(req.body.model, req.session.permission)) {
        res.send({ code: code.PERMISSION_NOT_ENOUGH });
        return;
    }
    let body = req.body;
    commonDao.findDataAndCount(body.model, body.startIndex, body.count, { 'isMain': -1, createTime: -1, '_id': -1 }, JSON.parse(body.matchData), function (err, result, totalCount) {
        if (!!err) {
            res.send({ code: err });
        } else {
            let arr = [];
            for (let i = 0; i < result.length; ++i) {
                arr.push(result[i]._doc);
            }
            res.send({ code: code.OK, msg: { recordArr: arr, totalCount: totalCount } });
        }
    })
});

router.post('/getUnion', function (req, res, next) {
    if (!req.session.uid) {
        res.send({ code: code.INVALID_UERS });
        return;
    }
    if (!checkRecordPermission(req.body.model, req.session.permission)) {
        res.send({ code: code.PERMISSION_NOT_ENOUGH });
        return;
    }
    let body = req.body;
    commonDao.findDataAndCount(body.model, body.startIndex, body.count, { 'isMain': -1, createTime: -1 }, JSON.parse(body.matchData), function (err, result, totalCount) {
        if (!!err) {
            res.send({ code: err });
        } else {
            let arr = [];
            for (let i = 0; i < result.length; ++i) {
                arr.push(result[i]._doc);
            }
            //查询机器人数
            async.map(arr, (unionData, cb) => {

                let unionID = unionData.unionID;
                commonDao.getDataCount('userModel', { 'unionID': unionID, 'isRobot': true }, (err, count) => {
                    unionData.robotCount = count;
                    cb(null, unionData);
                });

            }, (err, result) => {
                res.send({ code: code.OK, msg: { recordArr: result, totalCount: totalCount } });
            })
        }
    })
});



router.post('/updateRecord', function (req, res, next) {
    if (!req.session.uid) {
        res.send({ code: code.INVALID_UERS });
        return;
    }
    if (!checkRecordPermission(req.body.model, req.session.permission)) {
        res.send({ code: code.PERMISSION_NOT_ENOUGH });
        return;
    }

    let body = req.body;
    commonDao.updateData(body.model, JSON.parse(body.matchData), JSON.parse(body.saveData), function (err) {
        res.send({ code: !!err ? err : code.OK });

        recordChangeNotify(body.model);
    });
});

router.post('/addRecord', function (req, res, next) {
    if (!req.session.uid) {
        res.send({ code: code.INVALID_UERS });
        return;
    }
    if (!checkRecordPermission(req.body.model, req.session.permission)) {
        res.send({ code: code.PERMISSION_NOT_ENOUGH });
        return;
    }

    let body = req.body;
    let myData = JSON.parse(body.saveData);
    if (body.model == 'adminModel' && myData.password && myData.nickname && myData.permission) {
        myData.password = crypto.createHash('md5').update(myData.password, "utf-8").digest('hex');
    }
    commonDao.createData(body.model, myData, function (err) {
        res.send({ code: !!err ? err : code.OK });

        recordChangeNotify(body.model);
    });
});

router.post('/deleteRecord', function (req, res, next) {
    if (!req.session.uid) {
        res.send({ code: code.INVALID_UERS });
        return;
    }
    if (!checkRecordPermission(req.body.model, req.session.permission)) {
        res.send({ code: code.PERMISSION_NOT_ENOUGH });
        return;
    }

    let body = req.body;
    commonDao.deleteData(body.model, JSON.parse(body.matchData), function (err) {
        res.send({ code: !!err ? err : code.OK });

        recordChangeNotify(body.model);
    });
});

// -------------------------------------用户管理相关-----------------------------------
router.post('/grant', function (req, res, next) {
    if (!req.session.uid) {
        res.send({ code: code.INVALID_UERS });
        return;
    }
    if (!req.session.permission || (req.session.permission & enumeration.userPermissionType.USER_MANAGER) === 0) {
        res.send({ code: code.PERMISSION_NOT_ENOUGH });
        return;
    }


    if (req.session.permission == -1) {

        let updateData = {};
        updateData[req.body.field] = (parseInt(req.body.count) || 0);
        updateData = { $inc: updateData };
        userDao.updateUserData(req.body.uid, updateData, function (err) {
            if (!!err) {
                res.send({ code: code.REQUEST_DATA_ERROR });
            } else {
                res.send({ code: code.OK });
            }

            // 更新用户信息
            gameServerInterfaceServices.updateUserDataNotify(req.body.uid, [req.body.field], function (err) {
                if (!!err) {
                    console.error(err);
                }
            });

            // 创建赠送记录
            let saveData = {
                uid: req.session.uid,
                gainUid: req.body.uid,
                type: req.body.field,
                count: req.body.count,
                createTime: Date.now()
            };
            commonDao.createData("adminGrantRecordModel", saveData);
        });
    }

    // //查询是否今天已经赠送过
    // let daySart = new Date(new Date(new Date().toLocaleDateString()).getTime()).getTime();
    // let dayEnd = new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1).getTime();
    // let matchData = {
    //     uid: req.session.uid,
    //     gainUid: req.body.uid,
    //     type: req.body.field,
    //     createTime: { $gte: daySart, $lte: dayEnd }
    // }

    // commonDao.findOneData("adminGrantRecordModel", matchData, function (err, result) {
    //   else {
    //         res.send({ code: code.GOLD_DAY_LIMIT, message: '每个人每天只能赠送100' });
    //         return;
    //     }
    // });


});

router.post('/getOnlineUserData', function (req, res, next) {
    if (!req.session.uid) {
        res.send({ code: code.INVALID_UERS });
        return;
    }
    if (!req.session.permission || (req.session.permission & enumeration.userPermissionType.USER_MANAGER) === 0) {
        res.send({ code: code.PERMISSION_NOT_ENOUGH });
        return;
    }

    let startIndex = req.body.startIndex || 0;
    let count = req.body.count || 10;
    let uid = req.body.uid;

    if (!!uid) {
        userDao.getUserDataByUid(uid, function (err, result) {
            if (!!err) {
                res.send({ code: err });
            } else {
                res.send({ code: code.OK, msg: { recordArr: result && !!result.frontendId ? [result] : [], totalCount: 1 } });
            }
        })
    } else {
        userDao.getOnlineUserData(startIndex, count, function (err, recordArr, totalCount) {
            if (!!err) {
                res.send({ code: err });
            } else {
                res.send({ code: code.OK, msg: { recordArr: recordArr, totalCount: totalCount } });
            }
        })
    }
});

router.post('/updateUserData', function (req, res, next) {
    if (!req.session.uid) {
        res.send({ code: code.INVALID_UERS });
        return;
    }
    if (!req.session.permission || (req.session.permission & enumeration.userPermissionType.USER_MANAGER) === 0) {
        res.send({ code: code.PERMISSION_NOT_ENOUGH });
        return;
    }

    userDao.updateUserData(req.body.uid, JSON.parse(req.body.saveData), function (err) {
        res.send({ code: !!err ? err : code.OK });

        // 更新用户信息
        let updateKeys = [];
        let bodyData = JSON.parse(req.body.saveData);
        for (let key in bodyData) {
            if (bodyData.hasOwnProperty(key)) {
                updateKeys.push(key);
            }
        }
        gameServerInterfaceServices.updateUserDataNotify(req.body.uid, updateKeys, function (err) {
            if (!!err) {
                console.error(err);
            }
        })
    })
});

router.post('/updateUserDataEx', function (req, res, next) {
    if (!req.session.uid) {
        res.send({ code: code.INVALID_UERS });
        return;
    }
    if (!req.session.permission || (req.session.permission & enumeration.userPermissionType.USER_MANAGER) === 0) {
        res.send({ code: code.PERMISSION_NOT_ENOUGH });
        return;
    }

    userDao.updateUserDataEx(JSON.parse(req.body.matchData), JSON.parse(req.body.saveData), function (err) {
        res.send({ code: !!err ? err : code.OK });

        // 更新用户信息
        let updateKeys = [];
        let bodyData = JSON.parse(req.body.saveData);
        for (let key in bodyData) {
            if (bodyData.hasOwnProperty(key)) {
                updateKeys.push(key);
            }
        }
        gameServerInterfaceServices.updateUserDataNotify(req.body.uid, updateKeys, function (err) {
            if (!!err) {
                console.error(err);
            }
        })
    })
});


router.post('/mainData', function (req, res, next) {

    if (!req.session.uid) {
        res.send({ code: code.INVALID_UERS });
        return;
    }

    async.series({

        unionCount: (cb) => {
            commonDao.findDataAndCount('unionModel', 0, 1, {}, { 'isDel': { '$ne': true } }, function (err, result, totalCount) {
                let count = totalCount || 0;
                cb(null, count);
            })
        }, onlineUser: (cb) => {
            commonDao.findDataAndCount('userModel', 0, 1, {}, { 'isRobot': { '$ne': true }, 'frontendId': { '$ne': '' } }, function (err, result, totalCount) {
                let count = totalCount || 0;
                cb(null, count);
            })
        }, userCount: (cb) => {
            commonDao.findDataAndCount('userModel', 0, 1, {}, { 'isRobot': { '$ne': true } }, function (err, result, totalCount) {
                let count = totalCount || 0;
                cb(null, count);
            })
        }, userTodayCount: (cb) => {
            var now = Date.now();
            today = now - (now % (24 * 60 * 60 * 1000));
            commonDao.findDataAndCount('userModel', 0, 1, {}, { 'createTime': { '$gte': today }, 'isRobot': { '$ne': true } }, function (err, result, totalCount) {
                let count = totalCount || 0;
                cb(null, count);
            })
        },


    }, (err, result) => {

        res.send({ code: code.OK, msg: result });
    })


});

// -------------------------------------系统维护相关-----------------------------------
router.post('/sendSingleEmail', function (req, res, next) {
    if (!req.session.uid) {
        res.send({ code: code.INVALID_UERS });
        return;
    }
    if (!req.session.permission || (req.session.permission & enumeration.userPermissionType.USER_SYSTEM_MANAGER) === 0) {
        res.send({ code: code.PERMISSION_NOT_ENOUGH });
        return;
    }
    let uid = req.body.uid;
    let title = req.body.title;
    let content = req.body.content;
    if (!uid || !title || !content) {
        res.send({ code: code.REQUEST_DATA_ERROR });
        return;
    }

    userDao.getUserDataByUid(uid, function (err, userData) {
        if (!!err) {
            res.send({ code: err });
        } else {
            if (!userData) {
                res.send({ code: code.ACCOUNT_NOT_EXIST });
            } else {
                let emailArr = [];
                if (userData.emailArr.length > 0) emailArr = JSON.parse(userData.emailArr);
                emailArr.push({
                    id: Date.now().toString() + utils.getRandomNum(1000, 9999),
                    title: title,
                    content: content,
                    isRead: false,
                    status: enumeration.emailStatus.NOT_RECEIVE,
                    createTime: Date.now(),
                });
                userDao.updateUserData(uid, { emailArr: JSON.stringify(emailArr) }, function (err) {
                    if (!!err) {
                        console.error(err);
                    } else {
                        gameServerInterfaceServices.updateUserDataNotify(req.body.uid, ['emailArr'])
                    }
                });
                res.send({ code: code.OK });
            }
        }
    })
});

router.post('/sendAllServerEmail', function (req, res, next) {
    if (!req.session.uid) {
        res.send({ code: code.INVALID_UERS });
        return;
    }
    if (!req.session.permission || (req.session.permission & enumeration.userPermissionType.USER_SYSTEM_MANAGER) === 0) {
        res.send({ code: code.PERMISSION_NOT_ENOUGH });
        return;
    }
    let title = req.body.title;
    let content = req.body.content;
    if (!title || !content) {
        res.send({ code: code.REQUEST_DATA_ERROR });
        return;
    }

    commonDao.findOneData("configModel", { key: "systemEmail" }, function (err, result) {
        if (!err) {
            let systemEmail = null;
            if (!result) {
                systemEmail = [];
            } else {
                systemEmail = JSON.parse(result.value || "[]");
            }
            systemEmail.push({
                id: Date.now().toString() + utils.getRandomNum(1000, 9999),
                title: title,
                content: content,
                isRead: false,
                status: enumeration.emailStatus.NOT_RECEIVE,
                createTime: Date.now()
            });
            async.parallel([
                function (cb) {
                    commonDao.updateDataEx('configModel', { key: 'systemEmail' }, { value: JSON.stringify(systemEmail) }, { upsert: true }, function (err) {
                        cb(err);
                    });
                },
                function (cb) {
                    commonDao.updateDataEx('configModel', { key: 'lastUpdateSystemEmailTime' }, { value: Date.now() }, { upsert: true }, function (err) {
                        cb(err);
                    });
                }
            ], function (err) {
                res.send({ code: !!err ? err : code.OK });

                gameServerInterfaceServices.reloadParameterNotify(['publicParameter']);
            });
        } else {
            res.send({ code: err });
        }
    })
});

// -------------------------------------数据统计相关-----------------------------------
router.post('/getRechargeStatisticsInfoGroupByDay', function (req, res, next) {
    if (!req.session.uid) {
        res.send({ code: code.INVALID_UERS });
        return;
    }
    if (!req.session.permission || (req.session.permission & enumeration.userPermissionType.DATA_MANAGER) === 0) {
        res.send({ code: code.PERMISSION_NOT_ENOUGH });
        return;
    }

    recordDao.getRechargeStatisticsInfoGroupByDay(JSON.parse(req.body.matchData), function (err, result) {
        if (!!err) {
            res.send({ code: code.FAIL });
        } else {
            res.send({ code: code.OK, msg: { recordArr: result } });
        }
    });
});

router.post('/getRecordStatisticsInfo', function (req, res, next) {
    if (!req.session.uid) {
        res.send({ code: code.INVALID_UERS });
        return;
    }
    if (!req.session.permission || (req.session.permission & enumeration.userPermissionType.DATA_MANAGER) === 0) {
        res.send({ code: code.PERMISSION_NOT_ENOUGH });
        return;
    }

    let startTime = parseInt(req.body.startTime);
    let endTime = parseInt(req.body.endTime);
    let allUserCount = 0;
    let rechargeCount = 0;
    let totalRechargeNumber = 0;
    let gameProfitSum = 0;
    let inventoryExtractSum = 0;
    let inventoryModifySum = 0;
    let commissionExtractSum = 0;
    let withdrawCashSum = 0;
    let userGoldSum = 0;
    async.series([
        function (cb) {
            var findData = {
                createTime: { $gte: startTime, $lte: endTime }
            };
            // 获取注册总人数
            commonDao.getDataCount('userModel', findData, function (err, totalCount) {
                allUserCount = totalCount;
                cb(err);
            });
        },
        function (cb) {
            // 获取充值统计信息
            var findData = {
                createTime: { $gte: startTime, $lte: endTime }
            };
            recordDao.getRechargeStatisticsInfo(findData, function (err, resultArr) {
                if (!!err) {
                    cb(err);
                } else {
                    rechargeCount = resultArr.length;
                    for (var i = 0; i < resultArr.length; ++i) {
                        var result = resultArr[i];
                        totalRechargeNumber += result.total;
                    }
                    cb();
                }
            })
        },
        function (cb) {
            var findData = {
                day: { $gte: utils.getTimeDay(startTime), $lte: utils.getTimeDay(endTime) }
            };
            // 获取游戏抽水总额
            recordDao.getGameProfitStatisticsInfo(findData, function (err, resultArr) {
                if (!!err) {
                    cb(err);
                } else {
                    for (var i = 0; i < resultArr.length; ++i) {
                        var result = resultArr[i];
                        gameProfitSum += result.total;
                    }
                    cb();
                }
            })
        },
        function (cb) {
            // 获取库存抽取总额
            var findData = {
                createTime: { $gte: startTime, $lte: endTime }
            };
            recordDao.getInventoryExtractStatisticsInfo(findData, function (err, resultArr) {
                if (!!err) {
                    cb(err);
                } else {
                    for (var i = 0; i < resultArr.length; ++i) {
                        var result = resultArr[i];
                        inventoryExtractSum += result.total;
                    }
                    cb();
                }
            })
        },
        function (cb) {
            // 获取库存抽取总额
            var findData = {
                createTime: { $gte: startTime, $lte: endTime }
            };
            recordDao.getInventoryModifyStatisticsInfo(findData, function (err, resultArr) {
                if (!!err) {
                    cb(err);
                } else {
                    for (var i = 0; i < resultArr.length; ++i) {
                        var result = resultArr[i];
                        inventoryModifySum += result.total;
                    }
                    cb();
                }
            })
        },
        function (cb) {
            // 获取佣金提取总额
            var findData = {
                createTime: { $gte: startTime, $lte: endTime }
            };
            recordDao.getCommissionExtractStatisticsInfo(findData, function (err, resultArr) {
                if (!!err) {
                    cb(err);
                } else {
                    for (var i = 0; i < resultArr.length; ++i) {
                        var result = resultArr[i];
                        commissionExtractSum += result.total;
                    }
                    cb();
                }
            })
        },
        function (cb) {
            // 获取提现总额
            var findData = {
                createTime: { $gte: startTime, $lte: endTime }
            };
            recordDao.getWithdrawCashStatisticsInfo(findData, function (err, resultArr) {
                if (!!err) {
                    cb(err);
                } else {
                    for (var i = 0; i < resultArr.length; ++i) {
                        var result = resultArr[i];
                        withdrawCashSum += result.total;
                    }
                    cb();
                }
            })
        },
        function (cb) {
            // 玩家手头金币总额
            var findData = {
                createTime: { $gte: startTime, $lte: endTime }
            };
            recordDao.getUserGoldStatisticsInfo(findData, function (err, resultArr) {
                if (!!err) {
                    cb(err);
                } else {
                    for (var i = 0; i < resultArr.length; ++i) {
                        var result = resultArr[i];
                        userGoldSum += result.total;
                    }
                    cb();
                }
            })
        }
    ], function (err) {
        if (!!err) {
            console.error('getRecordStatisticsInfo err:' + err);
            res.send({ code: err });
        } else {
            res.send({
                code: code.OK, msg: {
                    allUserCount: allUserCount,
                    rechargeCount: rechargeCount,
                    totalRechargeNumber: totalRechargeNumber,
                    gameProfitSum: gameProfitSum,
                    inventoryExtractSum: inventoryExtractSum,
                    inventoryModifySum: inventoryModifySum,
                    commissionExtractSum: commissionExtractSum,
                    withdrawCashSum: withdrawCashSum,
                    userGoldSum: userGoldSum
                }
            });
        }
    });
});


router.post('/updateUnionData', function (req, res, next) {
    if (!req.session.uid) {
        res.send({ code: code.INVALID_UERS });
        return;
    }
    if (!req.body.matchData || !req.body.saveData) {
        res.send({ code: code.REQUEST_DATA_ERROR });
        return;
    }
    if (!req.session.permission || (req.session.permission & enumeration.userPermissionType.UNION_MANAGER) === 0) {
        res.send({ code: code.PERMISSION_NOT_ENOUGH });
        return;
    }

    commonDao.updateData("unionModel", JSON.parse(req.body.matchData), JSON.parse(req.body.saveData), function (err) {
        res.send({ code: !!err ? err : code.OK });
        if (!!req.body.unionID) {
            gameServerInterfaceServices.updateUnionDataNotify(req.body.unionID, function (err) {
                if (!!err) {
                    console.error(err);
                }
            })
        }
    })
});

router.post('/deleteUnion', function (req, res, next) {
    if (!req.session.uid) {
        res.send({ code: code.INVALID_UERS });
        return;
    }
    if (!req.body.unionID) {
        res.send({ code: code.REQUEST_DATA_ERROR });
        return;
    }
    if (req.session.permission !== -1) {
        res.send({ code: code.PERMISSION_NOT_ENOUGH });
        return;
    }

    //规还联盟机器人
    commonDao.updateAllData("userModel", { "unionID": req.body.unionID, 'isRobot': true }, { unionID: 0 }, function (err) {
        if (!!err) console.error(err);
    });


    // 删除联盟用户数据
    commonDao.updateAllData("userModel", { "unionInfo.unionID": req.body.unionID }, { $pull: { unionInfo: { unionID: req.body.unionID } } }, function (err) {
        if (!!err) console.error(err);

        // 通知服务器删除缓存
        gameServerInterfaceServices.retransmissionToGameServer("deleteUnionNotify", { unionID: req.body.unionID, permission: -1 }, function (err1) {
            if (!!err1) {
                console.error(err1);
            }

            res.send({ code: code.OK });
        });
    });
    // 删除联盟
    commonDao.deleteData("unionModel", { unionID: req.body.unionID }, function (err) {
        if (!!err) console.error(err);
    });
});


router.post('/union/setmian', function (req, res, next) {

    if (!req.session.uid) {
        res.send({ code: code.INVALID_UERS });
        return;
    }

    if (!req.body.unionID) {
        res.send({ code: code.REQUEST_DATA_ERROR });
        return;
    }

    let isMain = 0;
    if (parseInt(req.body.isMain) > 0) {
        isMain = Date.now();
    }
    // 删除联盟用户数据
    commonDao.updateData("unionModel", { "unionID": req.body.unionID }, { 'isMain': isMain }, function (err, result) {
        if (!!err) console.error(err);
        res.send({ code: code.OK });
    });

});


router.post('/bandaccount', function (req, res, next) {

    let data = req.body;
    // 查询用户数据
    commonDao.findOneData('accountModel', { account: data.account, uid: { '$ne': data.uid } }, function (err, userData) {

        if (!err && !userData) {
            commonDao.findOneAndUpdate('accountModel', { 'uid': data.uid }, { account: data.account, password: data.password }, (err, result) => {
                res.send({ code: 0, data: { err, result } });
            });

        } else {
            //数据不对
            let err = '账号已存在';
            res.send({ code: 0, data: { err } });
        }

    });


});

router.post('/getHeiBaiUser', function (req, res, next) {

    let data = req.body;

    let matchData = {};
    if (data.uid != "0") {
        matchData['uid'] = data.uid;
    }

    matchData['unionInfo.userType'] = parseInt(data.userType);

    let totalData = [{ $unwind: "$unionInfo" }, { $match: matchData }, { $group: { _id: null, totalCount: { $sum: 1 } } }];
    // 查询用户数据
    commonDao.nuwindData('userModel', totalData, function (err, userData) {

        let totalCount = (userData && userData[0] && userData[0].totalCount) || 0;
        let execData = [{ $unwind: "$unionInfo" }, { $match: matchData }, { '$skip': parseInt(data.startIndex) || 0 }, { '$limit': parseInt(data.count) || 10 }];

        // 查询用户数据
        commonDao.nuwindData('userModel', execData, function (err, userData) {

            if (!err && userData) {

                async.mapSeries(userData, function (curData, cb) {

                    let { uid, nickname, avatar } = curData;
                    let { unionID, userType } = curData.unionInfo;
                    //查询联盟数据
                    commonDao.findOneData('unionModel', { 'unionID': unionID }, function (err, unionData) {
                        let { ownerUid = null, ownerNickname = null, unionName = null } = unionData;
                        cb(null, { uid, nickname, ownerUid, ownerNickname, unionName, avatar, unionID, userType });
                    })

                }, function (err, result) {
                    res.send({ code: 0, msg: { recordArr: result, totalCount } });
                })


            } else {
                //数据不对
                res.send({ code: 0, data: [] });
            }

        });



    });



});


//添加账号
router.post('/addaccount', function (req, res, next) {

    let data = req.body;
    // 查询用户数据
    commonDao.findOneData('accountModel', { phoneAccount: data.account }, function (err, userData) {

        if (!err && !userData) {

            let uid = 0;
            let index = 100;

            async.doUntil(
                function (cb) {
                    index--;
                    uid = utils.getRandomNum(100000, 999999);
                    commonDao.findOneData("accountModel", { uid: uid }, function (err, result) {
                        if (!err && !result) {
                            cb(null, uid);
                        } else {
                            uid = 0;
                            cb(null);
                        }
                    });
                },
                function () { return index <= 0 || uid > 0; },
                function (err, uid) {
                    if (uid) {
                        let saveData = { uid: uid, phoneAccount: data.account, password: data.password };
                        commonDao.createData("accountModel", saveData, function (err, result) {
                            if (!err && result) {
                                saveData.nickname = data.nickname;
                                saveData.account = data.account;
                                saveData.createTime = Date.now();
                                commonDao.createData('userModel', saveData, (err, result) => {
                                    res.send({ code: 0, data: { err, result } });
                                });
                            }
                        });

                    } else {
                        res.send({ code: 0, data: { err: '请求失败' } });
                    }
                }
            );

        } else {
            //数据不对
            let err = '账号已存在';
            res.send({ code: 0, data: { err } });
        }

    });


});



module.exports = router;
